﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace XRGLib
{
    public static class Bresenham
    {
        /// <summary>
        /// Enumerates through each position along a line defined by the starting and ending points.
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public static IEnumerable<Point> GetLine(Point start, Point end)
        {
            return GetLine(start.X, start.Y, end.X, end.Y);
        }

        /// <summary>
        /// Enumerates through each position along a line defined by the starting and ending points.
        /// </summary>
        /// <param name="x0">Starting x coordinate</param>
        /// <param name="y0">Starting y coordinate</param>
        /// <param name="x1">Ending x coordinate</param>
        /// <param name="y1">Ending y coordinate</param>
        /// <returns></returns>
        public static IEnumerable<Point> GetLine(int x0, int y0, int x1, int y1)
        {
            int dx = Math.Abs(x1 - x0);
            int dy = Math.Abs(y1 - y0);
            int sx, sy;

            if (x0 < x1)
                sx = 1;
            else
                sx = -1;

            if (y0 < y1)
                sy = 1;
            else
                sy = -1;

            int err = dx - dy;

            while (true)
            {
                yield return new Point(x0, y0);
                if (x0 == x1 && y0 == y1)
                    break;

                int e2 = 2 * err;

                if (e2 > -dy)
                {
                    err = err - dy;
                    x0 = x0 + sx;
                }

                if (e2 < dx)
                {
                    err = err + dx;
                    y0 = y0 + sy;
                }
            }
        }

    }
}
